package com.uchiha.nova.mainService.filter;

import cn.hutool.core.util.StrUtil;
import com.uchiha.nova.mainService.provider.TokenProvider;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author 周林静
 * @Date 2022-12-31,0031 22:00
 * @Version 1.0
 */
@Slf4j
@Component
public class GetTokenFilterGatewayFilterFactory extends AbstractGatewayFilterFactory {
    @Override
    @SneakyThrows
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            //获取幂等token
            log.info("GetTokenFilter");
            ServerHttpResponse resp = exchange.getResponse();
            String url = exchange.getRequest().getQueryParams().getFirst("url");
            if(StrUtil.isNotEmpty(url)){
                return success(resp,url);
            }else{
                return missParam(resp);
            }
        };
    }



    private Mono<Void> success(ServerHttpResponse resp, String url) {
        resp.setStatusCode(HttpStatus.OK);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String result = TokenProvider.getTokenKey(url);

        DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }

    private Mono<Void> missParam(ServerHttpResponse resp) {
        resp.setStatusCode(HttpStatus.BAD_REQUEST);
        resp.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        String result = "缺少参数url";

        DataBuffer buffer = resp.bufferFactory().wrap(result.getBytes(StandardCharsets.UTF_8));
        return resp.writeWith(Flux.just(buffer));
    }
}
